package br.edu.unifei.mestrado.db.graph;

import org.neo4j.graphdb.Relationship;

import br.edu.unifei.mestrado.commons.graph.GraphProperties;
import br.edu.unifei.mestrado.commons.graph.NodeWrapper;
import br.edu.unifei.mestrado.commons.graph.RelationshipWrapper;
import br.edu.unifei.mestrado.commons.partition.AbstractPartition;

public class RelationshipDB implements RelationshipWrapper {

	private Relationship relationship;

	public RelationshipDB(Relationship relationship) {
		this.relationship = relationship;
	}

	@Override
	public NodeWrapper getEndNode() {
		return new NodeDB(relationship.getEndNode());
	}

	@Override
	public long getId() {
		Long id = (Long) relationship.getProperty(GraphProperties.ID);
		if (id == null) {
			throw new UnsupportedOperationException("Propriedade " + GraphProperties.ID
					+ " não encontrada para Relationship: " + relationship.getProperty(GraphProperties.ID));
		}
		return id;
	}

	@Override
	public NodeWrapper getOtherNode(NodeWrapper node) {
		return new NodeDB(relationship.getOtherNode(((NodeDB) node).getInnerNode()));
	}

	@Override
	public NodeWrapper getStartNode() {
		return new NodeDB(relationship.getStartNode());
	}

	@Override
	public int getWeight() {
		Integer peso = (Integer) relationship.getProperty(GraphProperties.PESO);
		if (peso == null) {
			throw new UnsupportedOperationException("Propriedade " + GraphProperties.PESO
					+ " não encontrada para Relationship: " + relationship.getProperty(GraphProperties.ID));
		}
		return peso;
	}

	@Override
	public boolean isRelationshipOnCut() {
		int p1 = (Integer)relationship.getStartNode().getProperty(GraphProperties.PARTITION);
		if(p1 == AbstractPartition.NO_PARTITION) {
			return false;
		}
		int p2 = (Integer)relationship.getEndNode().getProperty(GraphProperties.PARTITION);
		return p1 != p2;
	}

	public Relationship getInnerRelationship() {
		return relationship;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof RelationshipDB) {
			return relationship.equals(((RelationshipDB)obj).getInnerRelationship());
		}
		return false;
	}
	
	@Override
	public int hashCode() {
		return relationship.hashCode();
	}
	
	@Override
	public String toString() {
		return relationship.toString();
	}

}
